import os
import importlib
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from token_middleware import TokenMiddleware

app = FastAPI()

# 添加token验证中间件
app.add_middleware(TokenMiddleware)

# 配置静态文件服务
uploads_dir = os.path.join(os.path.dirname(__file__), 'uploads')
if os.path.exists(uploads_dir):
    app.mount("/uploads", StaticFiles(directory=uploads_dir), name="uploads")

# 自动注册pages目录下的路由
pages_dir = os.path.join(os.path.dirname(__file__), 'pages')
if os.path.exists(pages_dir):
    for filename in os.listdir(pages_dir):
        if filename.endswith('.py') and not filename.startswith('__'):
            module_name = f"pages.{filename[:-3]}"
            try:
                module = importlib.import_module(module_name)
                if hasattr(module, 'router'):
                    app.include_router(module.router)
            except Exception as e:
                print(f"Failed to load {module_name}: {e}")

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)